package com.sxfq.loansupermarket.backsystem.modular.theTest.controller;

import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.util.AmountUtils;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.modular.analysis.service.ICountServiceTwo;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.theTest.entity.ResponseDto;
import com.sxfq.loansupermarket.backsystem.modular.theTest.entity.TestQuestionsInfo;
import com.sxfq.loansupermarket.backsystem.modular.theTest.entity.TheTestInfo;
import com.sxfq.loansupermarket.backsystem.modular.theTest.factory.AppConstant;
import com.sxfq.loansupermarket.common.utils.DoubleUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author py
 * @Date 2018年2月4日23:05:54
 */
@Controller
@RequestMapping("/hamer")
public class hamerController extends BaseController {

    @Autowired
    private SqlMapper sqlMapper;
    @Autowired
    private ICountServiceTwo countServiceTwo;
    //判断是否是点击还是浏览   0 为浏览   1为点击
    private Integer stuts = null;

    @RequestMapping("")
    public String to_hamer(Model model) {
        return "/hamer.html";
    }

    @RequestMapping("/htest")
    public String htest(Model model) {
        return "/htest.html";
    }

    /**
     * 修改考试
     */
    @RequestMapping(value = "/get", method = RequestMethod.POST)
    public TestQuestionsInfo update() throws Exception {
        String theTestId = super.getPara("theTestId").trim();
        String index = super.getPara("index").trim();
        String sql = "     SELECT a.id,b.options_a,b.options_b, b.options_d,b.options_c,b.options_e,b.options_f, " +
                "        a.user_answer,a.test_questions_id,a.test_number,b.test_title,b.correct_answer " +
                "         from user_for_test_info a left join test_questions_info b on a.test_questions_id=b.id " +
                "        where 1=1  and the_test_id='" + theTestId + "' and user_id=" + ShiroKit.getUser().getId() +
                "        and test_number=" + index + "";
        TestQuestionsInfo testQuestionsInfoList = sqlMapper.selectOne(sql, TestQuestionsInfo.class);
        return testQuestionsInfoList;

    }


    /**
     * 首页bannar
     */
    @ApiOperation(value = "首页bannar", notes = "首页bannar",
            produces = "application/json; charset=utf-8")
    @RequestMapping(value = "getBannar", method = RequestMethod.GET)
    @ResponseBody
    public ResponseDto getBannar(HttpServletRequest request, String callback) {
        ResponseDto result = new ResponseDto();
        try {
            String source = "";
            StringBuilder sql = new StringBuilder();
            sql.append(" SELECT a.id ,a.title_img AS titleImg,a.link_state as linkState ,a.product_id as platformId,a.product_status as status ,if(link_state=0,concat(\"http://m.beadwallet.com/loansupermarket/#/loanplatformdetail?id=\",product_id,\"&status=\",product_status,\"&index=1\"),url) as url");
            sql.append(" FROM cms_content a WHERE 1=1 ");
            if ("0".equals(source)) {
                sql.append("AND a.id IN(403,404,405) ");
            } else {
                sql.append("AND a.`status` = 1 ");
            }
            sql.append("AND a.channel_id = '" + 2 + "' ");
            List<Map<String, Object>> list = sqlMapper.selectList(sql.toString());
            result.setCode(AppConstant.Code.SUCCESS);
            result.setMesg(AppConstant.Msg.SUCCESS);
            result.setData(list);
        } catch (Exception e) {
            result.setCode(AppConstant.Code.ERROR);
            result.setMesg(AppConstant.Msg.ERROR);
        }
        String results = "{'ret':'" + result + "'}";
        //加上返回参数
        results = callback + "(" + results + ")";
        return result;
    }

    /**
     * 跑马灯
     * 轮播用户借款成功记录
     */
    @ApiOperation(value = "跑马灯", notes = "跑马灯",
            produces = "application/json; charset=utf-8")
    @RequestMapping(value = "getBorrowRecord", method = RequestMethod.GET)
    @ResponseBody
    public ResponseDto getBorrowRecord(HttpServletRequest request) {
        ResponseDto result = new ResponseDto();
        try {
            StringBuilder sql = new StringBuilder();
            sql.append("SELECT ");
            sql.append("CONCAT('尾号', SUBSTR(b.phone, -4, 4), '用户在[', p.product_name, ']成功申请 ¥ ', IF(p.max_quato= 0, p.min_quato, p.max_quato)) AS note, ");
            sql.append("SUBSTR(phone,-4,4) AS phone, ");
            sql.append("p.product_name, ");
//        sql.append("expected_amount, ");
            sql.append("IF(p.max_quato= 0, p.min_quato, p.max_quato) as money ");
            sql.append("FROM `customer_application_record`  cb  ");
            sql.append("LEFT JOIN  `bw_borrower` b  on b.`id` =cb.`borrower_id`  ");
            sql.append("LEFT JOIN platform_product_info p ON cb.product_id= p.id  ");
            sql.append("WHERE 1=1 ");
            sql.append("AND b.phone IS NOT NULL AND b.phone <> '' ");
            sql.append("AND product_id IS NOT NULL ");
            sql.append("AND p.status = 1 ");
            sql.append("AND p.ifdel = 0 ");
            sql.append("ORDER BY RAND() DESC ");
            sql.append("LIMIT 100 ");
            List<Map<String, Object>> list = sqlMapper.selectList(sql.toString());
            result.setCode(AppConstant.Code.SUCCESS);
            result.setMesg(AppConstant.Msg.SUCCESS);
            result.setData(list);
        } catch (Exception e) {
            result.setCode(AppConstant.Code.ERROR);
            result.setMesg(AppConstant.Msg.ERROR);
        }
        return result;
    }

    /**
     * 明星产品
     */
    @ApiOperation(value = "明星产品列表", notes = "明星产品列表",
            produces = "application/json; charset=utf-8")
    @RequestMapping(value = "getStarProduct", method = RequestMethod.GET)
    @ResponseBody
    public ResponseDto getStarProduct(HttpServletRequest request) {
        ResponseDto results = new ResponseDto();
        String productType = "1";       // 产品类别（1.明星产品，2.广告产品）
        try {
            String sql = "  SELECT  p.id, p.product_img,p.product_name, p.min_quato,p.max_quato, p.lend_speed," +
                    "   FORMAT(p.daily_interest_rate,3) as daily_interest_rate" +
                    "  FROM platform_product_extra pe" +
                    "  LEFT JOIN platform_product_info p ON pe.product_id = p.id " +
                    " left join(SELECT * from platform_product_sort c where c.sort_type='99')as b on p.id=b.product_id " +
                    " left  JOIN platform_company_info d on p.company_id=d.id" +
                    " WHERE pe.product_type =  '" + 99 + "'" +
                    " AND p.status = 1   and p.ifdel!=1 and p.status =1 and d.status=1 and d.ifdel!=1 ORDER BY sort_num,p" +
                    ".create_time DESC";
//        sql= "  SELECT * from test";
            List<Map<String, Object>> applyList = sqlMapper.selectList(sql);
            List<Map<String, Object>> result = new ArrayList<>();
            for (Map<String, Object> map : applyList) {
                map.put("id", Integer.valueOf(map.get("id") + ""));
                map.put("product_name", StringUtil.toString(map.get("product_name")));// 公司名称
                map.put("product_img", StringUtil.toString(map.get("product_img")));// logo
                map.put("lend_speed", StringUtil.toString(map.get("lend_speed")) + "天");//  放款速度
                map.put("daily_interest_rate", getDailyInterestRate(StringUtil.toString(map.get("daily_interest_rate"))));// 日利息
                map.put("quato",
                        getQuatoChange(StringUtil.toString(map.get("min_quato")), StringUtil.toString(map.get
                                ("max_quato"))));// 放款额度
                // 查询标签
                map.remove("min_quato");
                map.remove("max_quato");
                result.add(map);
            }
            List<Map<String, Object>> list = result;
            results.setCode(AppConstant.Code.SUCCESS);
            results.setMesg(AppConstant.Msg.SUCCESS);
            results.setData(list);
        } catch (Exception e) {
            results.setCode(AppConstant.Code.ERROR);
            results.setMesg(AppConstant.Msg.ERROR);
        }
        return results;
    }

    /**
     * 去掉小数点后多余的0
     */
    private String getDailyInterestRate(String dailyInterestRate) {
        if (dailyInterestRate.indexOf(".") > 0) {
            //正则表达
            dailyInterestRate = dailyInterestRate.replaceAll("0+?$", "");//去掉后面无用的零
            dailyInterestRate = dailyInterestRate.replaceAll("[.]$", "");//如小数点后面全是零则去掉小数点
        }
        return dailyInterestRate;
    }

    /**
     * 到10000写万
     */
    private String getQuatoChange(String minQuato, String maxQuato) {
        String quato = "";
        DecimalFormat df = new DecimalFormat("#.00");
        if (!StringUtil.isEmpty(minQuato)) {
            if (Double.valueOf(minQuato) >= 10000) {
                quato = df.format(Double.valueOf(Double.valueOf(minQuato) / 10000)) + "万";
            } else {
                quato = DoubleUtil.toZeroDecimal(Double.valueOf(minQuato));
            }
        }
        if (!StringUtil.isEmpty(maxQuato) && !maxQuato.equals("0.00")) {
            //quato = DoubleUtil.toZeroDecimal(Double.valueOf(maxQuato));
            if (Double.valueOf(maxQuato) >= 10000) {
                quato = df.format(Double.valueOf(Double.valueOf(maxQuato) / 10000)) + "万";
            } else {
                quato = DoubleUtil.toZeroDecimal(Double.valueOf(maxQuato));
            }
        }
        if (!StringUtil.isEmpty(minQuato) && !StringUtil.isEmpty(maxQuato) && !maxQuato.equals("0.00")) {
            /*quato = DoubleUtil.toZeroDecimal(Double.valueOf(minQuato)) + "~"
                    + DoubleUtil.toZeroDecimal(Double.valueOf(maxQuato));*/
            if (Double.valueOf(minQuato) >= 10000 && Double.valueOf(maxQuato) >= 10000) {
                quato = df.format(Double.valueOf(Double.valueOf(minQuato) / 10000)) + "万~"
                        + df.format(Double.valueOf(Double.valueOf(maxQuato) / 10000)) + "万";
            } else if (Double.valueOf(minQuato) < 10000 && Double.valueOf(maxQuato) >= 10000) {
                quato = DoubleUtil.toZeroDecimal(Double.valueOf(minQuato)) + "~"
                        + df.format(Double.valueOf(Double.valueOf(maxQuato) / 10000)) + "万";
            } else if (Double.valueOf(minQuato) < 10000 && Double.valueOf(maxQuato) < 10000) {
                quato = DoubleUtil.toZeroDecimal(Double.valueOf(minQuato)) + "~"
                        + DoubleUtil.toZeroDecimal(Double.valueOf(maxQuato));
            }
        }
        return quato;
    }

    /***
     * 咨讯精选
     * @param request
     * @return
     */
    @ApiOperation(value = "咨讯精选", notes = "咨讯精选",
            produces = "application/json; charset=utf-8")
    @RequestMapping(value = "getIndexNews", method = RequestMethod.GET)
    @ResponseBody
    public ResponseDto getIndexNews(HttpServletRequest request) {
        ResponseDto result = new ResponseDto();
        //String cmsChannel = "152";       // 栏目类型
        try {
            StringBuilder sql = new StringBuilder();
            sql.append("SELECT ");
            sql.append("a.id, ");
            sql.append("a.url, ");
            sql.append("a.title, ");
            sql.append("a.create_time, ");
            sql.append("a.detail, ");
            sql.append("reads_count readsCount, ");
            sql.append("favor_count favorCount, ");
            sql.append("collect_count collectCount, ");
            sql.append("a.title_img as img ");
            sql.append("FROM cms_content a ");
            sql.append("WHERE 1=1 ");
            sql.append("AND a.`status` = 1 ");      // 内容是启用状态
//        sql.append("AND a.show_app_index = 1 ");    // 页面显示
            sql.append("AND a.channel_id IN ( + 157,158,159,160 + ) ");
            sql.append("ORDER BY a.create_time DESC LIMIT 3 ");
            List<Map<String, Object>> maps = sqlMapper.selectList(sql.toString());
            for (Map<String, Object> map : maps) {
                Integer readsCount = (Integer) map.get("readsCount");
                Integer favorCount = (Integer) map.get("favorCount");
                Integer collectCount = (Integer) map.get("collectCount");
                String readsTrans = AmountUtils.trans(readsCount);
                String favorTrans = AmountUtils.trans(favorCount);
                String collectTrans = AmountUtils.trans(collectCount);
                map.put("readsCount", readsTrans);
                map.put("favorCount", favorTrans);
                map.put("collectCount", collectTrans);
            }
            List<Map<String, Object>> list = maps;
            result.setCode(AppConstant.Code.SUCCESS);
            result.setMesg(AppConstant.Msg.SUCCESS);
            result.setData(list);
        } catch (Exception e) {
            result.setCode(AppConstant.Code.ERROR);
            result.setMesg(AppConstant.Msg.ERROR);
        }
        return result;
    }

    /**
     * 检验是否有活动更新
     */
    @ApiOperation(value = "用户活动更新", notes = "活动更新",
            produces = "application/json; charset=utf-8")
    @RequestMapping(value = "getUpdateActivity", method = RequestMethod.GET)
    @ResponseBody
    public ResponseDto getUpdateActivity(HttpServletRequest request, String token) {
        ResponseDto result = new ResponseDto();
        //String cmsChannel = "153";       // 栏目类型 活动
        try {
            //判断用户是否登录,未登录显示为有活动,有活动展示为1,没有活动为0
            if (StringUtil.isEmpty(token)) {
                result.setCode(AppConstant.Code.SUCCESS);
                result.setMesg(AppConstant.Msg.SUCCESS);
                result.setData(1);
            } else {
                //查询当前最大活动id
                Map activitymap = sqlMapper.selectOne("select max(id) id from cms_content where 1=1 and status = 1 and channel_id = #{channel_id}", 153);
                Integer is = 0;
                if (StringUtil.isNotEmpty(ShiroKit.getUser().getId())) {
                    //查询当前用户访问的活动的最大id
                    Map usermap = sqlMapper.selectOne("select max_activity_id maxActiId  from bw_borrower where id = #{id}", ShiroKit.getUser().getId());
                    if (StringUtil.isEmpty(usermap) || StringUtil.isEmpty(activitymap)) {
                        is = 1;
                    } else {
                        int userActivId = Integer.parseInt(usermap.get("maxActiId").toString());
                        int activity = Integer.parseInt(activitymap.get("id").toString());
                        if (userActivId < activity) {
                            is = 1;
                        } else {
                            is = 0;
                        }
                    }
                } else {
                    is = 1;
                }
                result.setCode(AppConstant.Code.SUCCESS);
                result.setMesg(AppConstant.Msg.SUCCESS);
                result.setData(is);
            }
        } catch (Exception e) {
            result.setCode(AppConstant.Code.ERROR);
            result.setMesg(AppConstant.Msg.ERROR);
        }
        return result;
    }

}
